package com.lzy.cloud.user.controller;

import com.lzy.cloud.user.dtos.ResourceDto;
import com.lzy.cloud.user.dtos.RoleDto;
import com.lzy.cloud.user.dtos.SysUserAdminDto;
import com.lzy.cloud.user.dtos.UserRoleDto;
import com.lzy.cloud.user.facade.SysUserAdminFacade;
import com.lzy.cloud.user.remote.BaseApi;
import com.lzy.cloud.user.remote.PermissionApi;
import com.lzy.cloud.user.remote.request.UserRoleRequest;
import com.lzy.cloud.user.request.LoginRequest;
import com.lzy.cloud.user.request.SysUserAdminRequest;
import com.lzy.cloud.user.response.SysUserAdminResponse;
import com.lzy.cloud.user.response.UserToken;
import com.lzy.cloud.user.service.SysUserAdminService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: 19516
 * @Despriction:
 * @Date: 2018-06-04 16:13
 */
@RestController
@Slf4j
public class SysUserAdminController{

    @Autowired
    private SysUserAdminService sysUserAdminService;

    @Autowired
    private SysUserAdminFacade sysUserAdminFacade;

    @Autowired
    private PermissionApi permissionApi;

    @Autowired
    private BaseApi baseApi;

    /**
     * 新增用户
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestHeader("token") String token, @RequestBody SysUserAdminRequest sysUserAdminRequest) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
        Ensure.that(sysUserAdminRequest.getLoginName()).isNotBlank("0000001");
        Ensure.that(sysUserAdminService.findByLoginName(sysUserAdminRequest.getLoginName())).isNull("0000002");
        SysUserAdminResponse sysUserAdminResponse = new SysUserAdminResponse();
        SysUserAdminDto sysUserAdminDto = DozerUtils.map(sysUserAdminRequest, SysUserAdminDto.class);
        sysUserAdminDto.setUserId(userToken.getId());
        sysUserAdminResponse.setId(sysUserAdminService.insert(sysUserAdminDto).toString());
        return new Result(sysUserAdminResponse);
    }

    /**
     * 登陆
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(LoginRequest loginRequest) {
        return new Result(sysUserAdminFacade.login(loginRequest));
    }

    /**
     * 校验token是否有效，有效则延续token有效期
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/verify", method = RequestMethod.GET)
    public Result verify(@RequestHeader("token") String token) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        return new Result(userToken == null ? 2 : 1);
    }

    /**
     * 查询用户的角色列表
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/role/list/by/user")
    public Result userRoleList(@RequestHeader("token") String token) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
        UserRoleRequest userRoleRequest = new UserRoleRequest();
        userRoleRequest.setUserId(userToken.getId());
        List<RoleDto> roleDtoList = new ArrayList<>();
        List<UserRoleDto> userRoleDtoList = DozerUtils.maps((List) permissionApi.selectUserRoleList(userRoleRequest).getResult(), UserRoleDto.class);
        for (UserRoleDto userRoleDto1 : userRoleDtoList) {
            roleDtoList.add(DozerUtils.map(permissionApi.selectRoleById(userRoleDto1.getRoleId()).getResult(), RoleDto.class));
        }
        roleDtoList.removeIf(o -> o == null);
        return new Result(roleDtoList);
    }

    /**
     * 查询用户的菜单权限
     *
     * @param roleId 角色id 若角色id不为空，仅查询该角色下的菜单权限
     * @param token
     * @return
     */
    @RequestMapping(value = "/menu/permission", method = RequestMethod.GET)
    public Result menuPermission(@RequestHeader("token") String token, @RequestParam(name = "roleId", required = false) Long roleId) {
        if (roleId != null) {
            return new Result(permissionApi.selectResourceListByRole(roleId));
        }
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
//        UserRoleRequest userRoleRequest = new UserRoleRequest();
//        userRoleRequest.setUserId(userToken.getId());
//        List<UserRoleDto> userRoleDtoList = (DozerUtils.maps(JSONArray.fromObject(permissionApi.selectUserRoleList(userRoleRequest).getResult()), UserRoleDto.class));
        List<UserRoleDto> userRoleDtoList = (DozerUtils.maps(JSONArray.fromObject(permissionApi.selectUserRoleListByUserId(userToken.getId()).getResult()), UserRoleDto.class));
        if (userRoleDtoList != null) {
            List<ResourceDto> resourceDtoList = new ArrayList<>();
            for (UserRoleDto roleDto : userRoleDtoList) {
                resourceDtoList.addAll(DozerUtils.maps((List) permissionApi.selectResourceListByRole(roleDto.getRoleId()).getResult(), ResourceDto.class));
            }
            /**
             * 利用set集合去重
             */
            return new Result(new HashSet<>(resourceDtoList));
        }
        return new Result();
    }

    /**
     * 查询某个菜单的功能权限
     *
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/feature/permissions/{menuId}", method = RequestMethod.GET)
    public Result featurePermissions(@PathVariable("menuId") Long menuId) {
        return permissionApi.selectPermissionByRes(menuId);
    }

    /**
     * 更新用户信息
     *
     * @param token
     * @param sysUserAdminRequest
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@RequestHeader("token") String token, @RequestBody SysUserAdminRequest sysUserAdminRequest) {
        Ensure.that(sysUserAdminRequest.getId()).isNotNull("0000007");
        /**
         * 不允许修改用户密码
         */
        sysUserAdminRequest.setPassword(null);
        Ensure.that(sysUserAdminService.update(DozerUtils.map(sysUserAdminRequest, SysUserAdminDto.class)) > 0).isTrue("0000008");
        return new Result(DozerUtils.map(sysUserAdminService.findById(sysUserAdminRequest.getId()), SysUserAdminResponse.class));
    }

    /**
     * 已知账号密码修改密码
     *
     * @param token
     * @param originalPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "/change/password", method = RequestMethod.POST)
    public Result changePassword(@RequestHeader("token") String token, @RequestParam("originalPassword") String originalPassword, @RequestParam("newPassword") String newPassword) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
        return new Result(sysUserAdminFacade.changePassword(userToken.getId(), originalPassword, newPassword));
    }

    /**
     * 更改用户状态
     *
     * @param token
     * @param userId
     * @param status 1正常 0禁用
     * @return
     */
    @RequestMapping(value = "/change/status/{userId}/{status}", method = RequestMethod.GET)
    public Result changeStatus(@RequestHeader("token") String token, @PathVariable("userId") Long userId, @PathVariable("status") Integer status) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
        SysUserAdminDto sysUserAdminDto = sysUserAdminService.findById(userId);
        Ensure.that(sysUserAdminDto).isNotNull("0000003");
        sysUserAdminDto.setState(status);
        sysUserAdminDto.setUserId(userToken.getId());
        return new Result(sysUserAdminService.update(sysUserAdminDto) > 0);
    }

    /**
     * 查询用户详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public Result detail(@PathVariable("id") Long id) {
        return new Result(DozerUtils.map(sysUserAdminService.findById(id), SysUserAdminResponse.class));
    }

    /**
     * 根据token查询用户信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/user/info", method = RequestMethod.GET)
    public Result userInfo(@RequestHeader("token") String token) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Ensure.that(userToken).isNotNull("0000006");
        Map<String, Object> map = new HashMap<>();
        map.put("info", DozerUtils.map(sysUserAdminService.findById(userToken.getId()), SysUserAdminResponse.class));
        map.put("permission", menuPermission(token, null).getResult());
        return new Result(map);
    }

    /**
     * 新增商户
     *
     * @return
     */
    @RequestMapping(value = "/user/add", method = RequestMethod.POST)
    public Result addUser(@RequestHeader("token") String token, @RequestBody SysUserAdminRequest sysUserAdminRequest) {
        UserToken userToken = DozerUtils.map(baseApi.isUserLogin(token).getResult(),UserToken.class);
        Boolean ok = sysUserAdminFacade.addUser(DozerUtils.map(sysUserAdminRequest,SysUserAdminDto.class));
        Ensure.that(ok).isTrue("");
        return new Result(ok);
    }

}
